package com.mercenary.wein.screenControl.test;

import com.android.ddmlib.*;
import com.mercenary.wein.screenControl.bean.CommandBean;
import com.mercenary.wein.screenControl.deviceControll.DeviceControlDecorator;
import com.mercenary.wein.screenControl.deviceControll.DevicesDetector;
import com.mercenary.wein.screenControl.deviceControll.AndroidDevice;
import com.mercenary.wein.screenControl.bean.DeviceBean;
import com.mercenary.wein.screenControl.service.DeviceService;
import com.mercenary.wein.screenControl.service.GroupService;
import com.mercenary.wein.screenControl.ui.util.Constants;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by tuxiao on 2017/2/26.
 */
public class ScrFrame {
    private JPanel src;



    public static void main(String[] args) throws AdbCommandRejectedException, IOException, TimeoutException {

        Log log = LogFactory.getLog(ScrFrame.class);
        log.info("init");

        final Map<String,DeviceControlDecorator> jspMap = new HashMap<String, DeviceControlDecorator>();
        final Map<String,AndroidDevice> choosedDevices = new HashMap<String, AndroidDevice>();
        final JPanel jp = new JPanel(new BorderLayout());
        final JPanel a = new JPanel();
        a.setLayout(new FlowLayout());
        jp.add(a,BorderLayout.CENTER);
        JMenuBar jmb = new JMenuBar();
        JMenuItem install = new JMenuItem("安装apk");
        install.addActionListener(new UploadListener("install",choosedDevices,jp));
        JMenuItem filePush = new JMenuItem("传输文件");
        filePush.addActionListener(new UploadListener("push",choosedDevices,jp));
        jmb.add(install);
        jmb.add(filePush);

        //==========
        JMenuItem test = new JMenuItem("发送命令");
        test.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
//                new GroupService().sendCommondByGId(0,new CommandBean(1,"2","sdfs"));
            }
        });
        jmb.add(test);
        //===========

        jp.add(jmb,BorderLayout.NORTH);
        JFrame frame = new JFrame("ScrFrame");
        frame.setMinimumSize(new Dimension(1000,1000));
        frame.setContentPane(jp);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
        DevicesDetector devicesDetector = DevicesDetector.getInstance();

        DeviceService deviceService = new DeviceService();
        int i=0;
        for(AndroidDevice androidDevice:devicesDetector.getDevicesMap().values()){
            //TODO 一个bug，连接时间长后悔出现若干个模拟器，怀疑是monkey的干扰
            if(androidDevice.getSerialNo().startsWith("emulator"))continue;
            DeviceBean deviceBean = deviceService.registerDevice(androidDevice);
            androidDevice.getDevice().createForward(deviceBean.getPort(),3321);
            try {
                androidDevice.getDevice().executeShellCommand("am start -n com.zoke.wechatautomate/com.zoke.wechatautomate.MainActivity", new IShellOutputReceiver() {
                    public void addOutput(byte[] data, int offset, int length) {
                    }
                    public void flush() {
                    }
                    public boolean isCancelled() {
                        return false;
                    }
                });
            } catch (ShellCommandUnresponsiveException e) {
                e.printStackTrace();
            }
//            MyPanel myPanel = new MyPanel(androidDevice.getDevice(),deviceBean.getPort());
//            myPanel.setPreferredSize(new Dimension(270,480));
//            a.add(myPanel);

//            DeviceControlDecoratorPlus dcd = new DeviceControlDecoratorPlus(androidDevice,deviceBean.getPort());
            DeviceControlDecorator dcd = new DeviceControlDecorator(androidDevice);
            a.add(dcd);
            a.updateUI();
//            jspMap.put(androidDevice.getSerialNo(),dcd);
            choosedDevices.put(androidDevice.getSerialNo(),androidDevice);
//            OperateAndroid oa = new OperateAndroid(androidDevice.getDevice());
//            OperateAndroid.injectListener(panelScreen,oa);
        }


        devicesDetector.setConnectedListener(new DevicesDetector.DeviceConnectedListener() {
            public void handler(AndroidDevice androidDevice) {
                if(androidDevice.getSerialNo().startsWith("emulator"))return;
                DeviceControlDecorator dcd = new DeviceControlDecorator(androidDevice);
                a.add(dcd);
                a.updateUI();
                System.out.println("end init");
                jspMap.put(androidDevice.getSerialNo(),dcd);
                choosedDevices.put(androidDevice.getSerialNo(),androidDevice);
            }
        });
        devicesDetector.setDisConnectedListener(new DevicesDetector.DeviceDisConnectedListener() {
            public void handler(AndroidDevice androidDevice) {
                a.remove(jspMap.get(androidDevice.getSerialNo()));
                jspMap.remove(androidDevice.getSerialNo());
                choosedDevices.remove(androidDevice.getSerialNo());
                androidDevice.stopScreenCaptureThread();
                a.repaint();
            }
        });


    }



}

class UploadListener implements ActionListener{
    private String action;
    private Map<String,AndroidDevice> androidDevices;
    private Component whereShow;
    private ExecutorService handlePool = Executors.newFixedThreadPool(30);
    public UploadListener(String action,Map<String,AndroidDevice> androidDevices,Component whereShow){
        this.action = action;
        this.androidDevices = androidDevices;
        this.whereShow = whereShow;
    }
    public void actionPerformed(ActionEvent e) {
        JFileChooser fc = new JFileChooser();
        fc.setDialogTitle("请选择要上传的文件...");
        fc.setApproveButtonText("确定");
        fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
        if (JFileChooser.APPROVE_OPTION == fc.showOpenDialog(whereShow)) {
            final String path=fc.getSelectedFile().getPath();
            if(action.equals("push")){
                final File file = new File(path);
                final String fileName = file.getName();
                for (final Map.Entry<String,AndroidDevice> ad:androidDevices.entrySet()){
                    handlePool.execute(new Runnable() {
                        public void run() {
                            ad.getValue().pushFile(file, Constants.DeviceFilePath+fileName);
                            try {
                                ad.getValue().getDevice().executeShellCommand("am broadcast -a android.intent.action.MEDIA_SCANNER_SCAN_FILE -d file:///storage/sdcard0/Download/"+fileName,new NullOutputReceiver());
                            } catch (TimeoutException e1) {
                                e1.printStackTrace();
                            } catch (AdbCommandRejectedException e1) {
                                e1.printStackTrace();
                            } catch (ShellCommandUnresponsiveException e1) {
                                e1.printStackTrace();
                            } catch (IOException e1) {
                                e1.printStackTrace();
                            }
                        }
                    });
                }
            }else if(action.equals("install")){
                for (final Map.Entry<String,AndroidDevice> ad:androidDevices.entrySet()){
                    handlePool.execute(new Runnable() {
                        public void run() {
                            ad.getValue().installAPK(path);
                        }
                    });
                }
            }
        }
    }

}